import { Body, Controller, Post,HttpCode, Get, Query } from '@nestjs/common';
import { ApiParam, ApiProperty, ApiTags } from '@nestjs/swagger';
import axios from 'axios';
import { sha1 } from '../utils/hash'

const appid ='wx455f944a2cdf48ff'
const secret = '1d84b46003ffff85347e39c02df51023'

class AuthDto {
  @ApiProperty()
  code: string
}

@Controller('wechat')
@ApiTags('微信')
export class WechatController {

  @Post('/auth')
  @HttpCode(200)
  async wechat(@Body() auth:AuthDto) {
    let {data: {access_token, openid}} = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
      params: {
        appid,
        secret,
        grant_type: 'authorization_code',
        code: auth.code
      }
    })

    if (access_token) {
      let {data} = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
        params: {
          access_token,
          openid
        }
      })
      return data
    } else {
      return {
        msg: 'error'
      }
    }
  }

  @Get('jweixin/config')
  @HttpCode(200)
  async config(@Query('url') url:string) {
    const params = {
      grant_type: 'client_credential',
      appid,
      secret
    }
    let {data:{access_token}} = await axios.get('https://api.weixin.qq.com/cgi-bin/token', { params })
    let {data: {ticket}} = await axios.get('https://api.weixin.qq.com/cgi-bin/ticket/getticket', {
      params: {
        access_token,
        type: 'jsapi'
      }
    })
    let noncestr = 'abc'
    let timestamp = Math.floor(new Date().valueOf() / 1000)
    let s = `jsapi_ticket=${ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`
    return {
      appId: appid,
      timestamp: timestamp,
      nonceStr: noncestr,
      signature: sha1(s, 'utf-8', 'hex'),
      jsApiList: [ 'chooseImage', 'openLocation', 'uploadImage'],
      debug: true
    }
  }
}


